package com.kkb.dynamiproxy;

import com.kkb.service.BookService;
import com.kkb.service.IService;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MyJDKProxy {
    public static void main(String[] args) {
        //目标对象--被代理对象
        BookService bookService = new BookService();
        //返回代理对象 调用JDK中Proxy类中的静态方法newProxyInstance获取动态代理类的实例
        IService proxyService = (IService) Proxy.newProxyInstance(
                bookService.getClass().getClassLoader(),
                bookService.getClass().getInterfaces(),
                new InvocationHandler() {//回调函数，编写代理规则
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        try {
                            System.out.println("开始事务");
                            Object invoke = method.invoke(bookService, args);//核心业务
                            System.out.println("提交事务");
                            return invoke;
                        } catch (Exception e) {
                            System.out.println("回滚事务");
                            e.printStackTrace();
                            throw e;
                        } finally {
                            System.out.println("finally--------");
                        }
                    }
                }
        );

        //代理对象干活
        proxyService.add();
        System.out.println(bookService.getClass());
        System.out.println(proxyService.getClass()+"-----------");
    }
}
